<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.maintenancePlan_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.maintenancePlan_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" v-if="permission.maintenancePlan_view" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.maintenancePlan_edit" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" v-if="permission.maintenancePlan_delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
      <template slot-scope="{ row }" slot="enabled">
        <el-tag :class="row.enabled ? 'successTag' : 'dangerTag'">{{ row.enabled ? '是' : '否' }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog
      v-dragDirectives
      ref="dialog"
      :title="dialogTitle"
      append-to-body
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      top="5vh"
      height="80%"
      @close="closeDialog"
    >
      <avue-form ref="basicInfo" v-if="showDialog" v-model="form" :option="dialogOption">
        <template slot="cycle">
          <div class="cycle-style">
            <el-input placeholder="请选择养护周期" v-model="form.cycle" :disabled="dialogTitle == '详情'"> </el-input>
            <el-select style="width: 120px !important" v-model="form.cycleUnit" placeholder="" :disabled="dialogTitle == '详情'">
              <el-option v-for="item in cycleList" :key="item.label" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </div>
        </template>
      </avue-form>
      <avue-crud :option="equipmentOption" :data="equipmentData" @selection-change="selectionDetailChange" @row-click="handleRowClick">
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" :disabled="dialogTitle != '详情' ? false : true" @click="addEquipmentDetail()">新 增 </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" plain :disabled="dialogTitle != '详情' ? false : true" @click="handleDetailDelete()">删 除 </el-button>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import { getList, getDetail, add, remove } from '@/api/equipment-manage/maintenance-plan';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import userConfig from '@/mixins/userConfig';
import userTableConfig from '@/components/user-table-config';
export default {
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'MAINTENANCE_PLAN',
      form: {
        cycleUnit: 'DAY'
      },
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      cycleList: [
        {
          label: '年',
          value: 'YEAR'
        },
        {
          label: '月',
          value: 'MONTH'
        },
        {
          label: '天',
          value: 'DAY'
        },
        {
          label: '周',
          value: 'WEEK'
        }
      ],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '计划编码',
            prop: 'code',
            search: true
          },
          {
            label: '计划名称',
            prop: 'name',
            search: true
          },
          {
            label: '负责人',
            prop: 'principleName'
          },
          {
            label: '生效日期',
            prop: 'startDate',
            type: 'date',
            format: 'yyyy-MM-dd'
          },
          {
            label: '启用',
            prop: 'enabled',
            type: 'switch',
            // value: true,
            // dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '计划编码',
            prop: 'code',
            search: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '计划名称',
            prop: 'name',
            search: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '负责人',
            prop: 'principleName',
            type: 'search',
            span: 8,
            disabled: true,
            placeholder: '请选择 负责人',
            appendClick: () => {
              if (this.dialogTitle === '详情') return;
              this.openPrincipalCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择负责人',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '养护周期',
            prop: 'cycle',
            hide: false,
            span: 8,
            rules: [
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value) {
                    let reg = /^[1-9]\d*$/g;
                    if (!reg.test(value)) {
                      callback(new Error('养护周期为数字，不能小于等于0，并且是整数'));
                    } else {
                      callback();
                    }
                  } else {
                    callback(new Error('请输入养护周期'));
                  }
                }
              }
            ]
          },
          {
            label: '生效日期',
            prop: 'startDate',
            type: 'date',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            span: 8,
            pickerOptions: {
              disabledDate: (time) => {
                console.log(time);
                return time.getTime() < new Date(1970 - 1 - 1).getTime() || time.getTime() < Date.now() - 3600 * 1000 * 24; //禁止选择1970年以前的日期
              }
            },
            rules: [
              {
                required: true,
                message: '请选择生效日期',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '启用',
            prop: 'enabled',
            type: 'switch',
            span: 8,
            // value: true,
            // dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            hide: true,
            type: 'textarea',
            minRows: 3,
            maxRows: 3,
            span: 8
          }
        ]
      },
      equipmentOption: {
        height: 350,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menu: false,
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '设备名称',
            prop: 'equipmentName',
            rules: [
              {
                required: true,
                message: '请输入设备名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '设备编码',
            prop: 'equipmentCode',
            rules: [
              {
                required: true,
                message: '请输入设备编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '设备型号',
            prop: 'categoryName'
          },
          {
            label: '设备类型',
            prop: 'model'
          }
        ]
      },
      timer: new Date().getTime(),
      tableOption: {},
      equipmentData: [],
      selectionDetailList: [],
      equipmentClickIndex: 0
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.maintenancePlan_add, false),
        viewBtn: this.vaildData(this.permission.maintenancePlan_view, false),
        delBtn: this.vaildData(this.permission.maintenancePlan_delete, false),
        editBtn: this.vaildData(this.permission.maintenancePlan_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids.join(','));
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.type = 'MAINTAIN_PLAN';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.form.cycleUnit = 'DAY';
      this.form.enabled = true;
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = false;
      });
    },
    openPrincipalCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    /**
     * 打开设备选择模版
     */
    addEquipmentDetail() {
      this.modalName = 'equipmentModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择设备信息（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'multiple',
        columnDefs: [
          {
            label: '设备名称',
            prop: 'name',
            search: true
          },
          {
            label: '设备编码',
            prop: 'code',
            search: true
          },
          {
            label: '设备型号',
            prop: 'model'
          },
          {
            label: '设备类型',
            prop: 'categoryName'
          },
          {
            label: '设备类型',
            prop: 'categoryId',
            search: true,
            hide: true,
            type: 'select',
            dicUrl: '/api/mes-product/ems-equipment-category/page?current=1&size=100',
            props: {
              label: 'name',
              value: 'id'
            },
            dicFormatter: (data) => {
              return data.data.records;
            }
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalModal':
          //   let principle = [];
          //   let principleName = [];
          //   this._forEach(rowData, (item) => {
          //     principle.push({ id: this._get(item, 'id', ''), name: this._get(item, 'realName', '') });
          //     principleName.push(this._get(item, 'realName', ''));
          //   });
          this.$set(this.form, 'principle', this._get(rowData, 'id', ''));
          this.$set(this.form, 'principleName', this._get(rowData, 'realName', ''));
          break;
        case 'equipmentModal':
          let flag = this._some(this.equipmentData, (item1) => {
            return this._some(rowData, (item2) => {
              return item1['equipmentCode'] === item2['code'];
            });
          });
          if (flag) {
            this.$message({
              type: 'warning',
              message: '选择的设备与已选的设备有重复,请重新选择'
            });
          } else {
            this._forEach(rowData, (item) => {
              let equipmentInfo = {
                equipmentCode: this._get(item, 'code', ''),
                equipmentName: this._get(item, 'name', ''),
                equipmentId: this._get(item, 'id', ''),
                model: this._get(item, 'model', ''),
                categoryName: this._get(item, 'categoryName', '')
              };
              this.equipmentData.push(equipmentInfo);
            });
          }
          break;
      }
    },
    selectionDetailChange(list) {
      this.selectionDetailList = list;
    },
    closeDialog() {
      this.equipmentData = [];
    },
    handleRowClick(row) {
      this.equipmentClickIndex = row.$index;
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.basicInfo.validate((valid, done) => {
        if (valid) {
          if (this.equipmentData.length === 0) {
            this.$message({
              type: 'warning',
              message: '请选择设备！'
            });
            return;
          }
          this.form.type = 'MAINTAIN_PLAN';
          //   this.form.cycleDay = Number(this.form.cycleDay);
          this.form.equipmentCheckRelationList = this.equipmentData;
          this.form.startDate = this.form.startDate + ' 00:00:00';
          add(this.form).then((res) => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            this.showDialog = false;
          });
          done();
        }
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.equipmentData = this._get(this.form, 'equipmentVOList', []).map((item) => {
          return {
            ...item,
            equipmentCode: item.code,
            equipmentName: item.name,
            equipmentId: item.id
          };
        });
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfo.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.equipmentData = this._get(this.form, 'equipmentVOList', []).map((item) => {
          return {
            ...item,
            equipmentCode: item.code,
            equipmentName: item.name,
            equipmentId: item.id
          };
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    closeDialog() {
      this.$refs.basicInfo.resetFields();
      this.form = {};
      this.equipmentData = [];
    },
    /**
     * 删除设备信息
     */
    handleDetailDelete() {
      let selectId = [];
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          for (let i = 0; i < this.selectionDetailList.length; i++) {
            for (let j = 0; j < this.equipmentData.length; j++) {
              if (this.selectionDetailList[i].equipmentCode === this.equipmentData[j].equipmentCode) {
                this.equipmentData.splice(j, 1);
              }
            }
          }
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    }
  }
};
</script>
<style scoped>
.cycle-style {
  display: flex;
  flex-direction: row;
}
</style>
